package com.baosight.risk.service.xtzy.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.api.xtzy.IXtzyOrgService;
import com.baosight.risk.api.xtzy.IXtzyRoleShiftService;
import com.baosight.risk.api.xtzy.IXtzyRoleUserService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.redis.BaseRedis;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.system.SysRoleMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompRoleMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.mapper.xtzy.XtzyRoleUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.xtzy.bo.XtzyRoleUserReplaceBO;
import com.baosight.risk.service.xtzy.entity.XtzyCompUser;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyOrg;
import com.baosight.risk.service.xtzy.entity.XtzyRoleUser;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.vo.XtzyCompUserVO;
import com.baosight.risk.service.xtzy.vo.XtzyCompanyVO;
import com.baosight.risk.service.xtzy.vo.XtzyUserVO;

/**
 * 类 名: XtzyRoleUserServiceImpl
 * 描 述:
 * 作 者: 黎秋荣
 * 创 建：2019年05月22日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Service
public class XtzyRoleUserServiceImpl extends BaseServiceImpl<XtzyRoleUser> implements IXtzyRoleUserService {
    @Autowired
    private XtzyRoleUserMapper roleUserMapper;
    @Autowired
    private XtzyCompUserMapper compUserMapper;
    @Autowired
    private XtzyUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private XtzyCompanyMapper companyMapper;
    @Autowired
    private IXtzyCompanyService xtzyCompanyService;
    @Autowired
    private IXtzyUserService userService;
    @Autowired
    private BaseRedis redis;
    @Autowired
    private IXtzyRoleShiftService roleShiftService;
    @Autowired
    private XtzyCompRoleMapper compRoleMapper;
    @Autowired
    private IXtzyCompanyService companyService;
    @Autowired
    private IXtzyOrgService xtzyOrgService;
    
    
    @Override
    public BaseMapper getMapper() {
        return roleUserMapper;
    }

    @Override
    public List<XtzyUserVO> queryUserRole(String compId, String userDesc, String userCode) {
        //根据组织查找所有用户
        List<XtzyUserVO> userVOList = compUserMapper.getUserByCompId(compId, userDesc, userCode);
        //找出所有当前组织下的用户角色 (减少数据库查询次数)
        List<XtzyRoleUser> roleUserLis = roleUserMapper.getRoleByCompIdAndUserId(compId, null);
        if (!CollectionUtils.isEmpty(userVOList)) {
//            //根据组织和用户查询用户所属角色
            for (XtzyUserVO userVO : userVOList) {
                String compCode = compId;
                if (compCode == null) {
                    compCode = userVO.getExt3();
                }
//                List<XtzyRoleUser> roleLis = roleUserMapper.getRoleByCompIdAndUserId(compCode, userVO.getId());
                String finalCompCode = compCode;
                List<XtzyRoleUser> roleLis = roleUserLis.stream()
                        .filter(r -> StringUtils.equals(r.getCompCode(), finalCompCode) && StringUtils.equals(r.getUserGuid(), userVO.getId()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(roleLis)) {
                    userVO.setRoleuserList(roleLis);
                }
//                List<SysRole> roleList = roleMapper.selectRoleByCompIdAndUserId(compId,userVO.getId());
//                if (!CollectionUtils.isEmpty(roleList)){
//                    userVO.setRoleList(roleList);
//                }
            }
        }
        return userVOList;
    }

    @Override
    public List<XtzyUserVO> queryAppointUserRole(String compId, String userDesc, String userCode) {

        List<String> roleList=new ArrayList<>();
        roleList.add("4430017a-4446-4b1f-8996-cdfa1a030284");
        roleList.add("56c21cb0-2b7e-4947-9a0e-dde4d6189ae6");
        roleList.add("25da0cae-eb46-407c-823d-3a894ea9c448");

        List<XtzyRoleUser> roleUserLis = roleUserMapper.getRoleByCompIdAndRole(compId, roleList);
        List<XtzyUserVO> users=new ArrayList<>();
        if (!CollectionUtils.isEmpty(roleUserLis)) {
            //根据组织查找所有用户
            List<XtzyUserVO> userVOList = compUserMapper.getUserByCompId(compId, userDesc, userCode);
            for(XtzyUserVO userVO:userVOList){
                for (XtzyRoleUser roleUser:roleUserLis){
                    if (userVO.getUserCode().equals(roleUser.getUserCode())){
                        users.add(userVO);
                    }
                }
            }
            users = users.stream().collect(Collectors.collectingAndThen(
            		Collectors.toCollection(() -> new TreeSet<XtzyUserVO>(Comparator.comparing(XtzyUserVO::getUserCode))), ArrayList<XtzyUserVO>::new));
            return users;
        }else{
            return new ArrayList<>();
        }

    }

    @Override
    public List<XtzyRoleUser> selectRoleUserList(String compId, String roleKey){
        List<String> roleList=new ArrayList<>();
        roleList.add(roleKey);
        return roleUserMapper.getRoleByCompIdAndRole(compId, roleList);
    }

    /**
     * 根据组织获取指定用户所属角色
     *
     * @param compId 组织ID
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<SysRole> getUserRoles(String compId, String userId) {
        List<SysRole> roleList = roleMapper.selectRoleByCompIdAndUserId(compId, userId);
        return roleList;
    }

    /**
     * 根据组织获取指定用户所属角色
     *
     * @param compCodes 组织ID
     * @param userId    用户编码
     * @return
     */
    @Override
    public List<SysRole> getRolesByUserCode(List<String> compCodes, String userId) {
        List<SysRole> roleList = roleMapper.selectRoleByCompIdAndUserCode(compCodes, userId);
        return roleList;
    }

    @Override
    public Integer saveCompUser(XtzyCompanyVO companyVO) {
        redis.deleteList("auth:");
        XtzyCompany company = companyMapper.selectByPrimaryKey(companyVO.getCompCode());
        for (XtzyUser user : companyVO.getUserList()) {
            //判断用户在数据库是否已经存在,已存在的不新增
            XtzyCompUser compUser = compUserMapper.getUserByCompIdAndUser(company.getCompCode(), user.getUserCode());
            if (null != compUser) {
                continue;
            }
            compUser = new XtzyCompUser();
            compUser.setUserId(user.getId());
            compUser.setUserCode(user.getUserCode());
            compUser.setUserDesc(user.getUserDesc());
            compUser.setCompId(company.getId());
            compUser.setCompCode(company.getCompCode());
            compUser.setCompName(company.getCompName());
            compUser.setPathCode(company.getPathCode());
            compUser.setPathName(company.getPathName());
            compUser = (XtzyCompUser) BeanUtils.initBean(compUser);
            compUserMapper.insert(compUser);
        }
        return 1;
    }


    @Override
    public Integer deleteCompUser(String id) {
        XtzyCompUser compUser = compUserMapper.selectByPrimaryKey(id);
        if (null == compUser) {
            compUser = new XtzyCompUser();
        }
        redis.deleteList("auth:");
        //先删除人员角色的授权关系
        roleUserMapper.deleteByCompIdAndUserId(compUser.getCompId(), compUser.getUserId());
        //删除人员
        return compUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public Integer saveUserRole(XtzyCompanyVO companyVO) throws Exception{
        redis.deleteList("auth:");
        for (XtzyUser user : companyVO.getUserList()) {
            //先删除用户的角色信息==组织、用户、角色关系
            roleUserMapper.deleteByCompIdAndUserId(companyVO.getId(), user.getId());
            for (SysRole role : companyVO.getRoleList()) {
            	XtzyRoleUser roleUser = new XtzyRoleUser();
                
                SysRole rl = roleMapper.selectByPrimaryKey(role.getId());
                if("Y".equals(rl.getUniqueFlag())){
                	XtzyRoleUser param = new XtzyRoleUser();
                	param.setCompCode(companyVO.getId());
                	param.setRoleCode(role.getId());
                	int count = roleUserMapper.selectCount(param);
                	if(count>0){
                		throw new Exception(rl.getRoleName()+",角色具有唯一性，不能添加!");
                	}
                }
                String roleTypeCode = rl.getRoleTypeCode();
                if(roleTypeCode!=null && roleTypeCode.startsWith("ORG")){
                	XtzyCompany mCompany = companyService.getManageCompany(role.getExt1());
                	XtzyOrg org = xtzyOrgService.getOneByMangeCompCode(mCompany.getCompCode(), roleTypeCode);
                	if(org!=null){
                    	roleUser.setBusiOrgCode(org.getBusiOrgCode());
                    	roleUser.setBusiOrgName(org.getBusiOrgName());
                	}
                }
                
                roleUser.setRoleCode(role.getId());
                roleUser.setRoleName(role.getRoleName());
                roleUser.setRoleCompCode(role.getExt1());
                roleUser.setRoleCompName(role.getExt2());
                roleUser.setUserGuid(user.getId());
                roleUser.setUserCode(user.getUserCode());
                roleUser.setUserDesc(user.getUserDesc());
                roleUser.setCompCode(companyVO.getId());
                roleUser.setCompName(companyVO.getCompName());
                roleUser.setPathName(companyVO.getPathName());
                roleUser.setPathCode(companyVO.getPathCode());
                roleUser = (XtzyRoleUser) BeanUtils.initBean(roleUser);
                roleUserMapper.insert(roleUser);
            }

        }

        return 1;
    }


    @Override
    public List<XtzyUser> getRoleByRoleIdAndCompId(String compId, String roleId) {
        return userMapper.getRoleByRoleIdAndCompId(compId, roleId);
    }

    @Override
    public List<XtzyRoleUser> getRoleByCompId(String compId) {
        return roleUserMapper.getRoleByCompId(compId);
    }

    @Override
    public List<XtzyRoleUser> selectByUserCode(XtzyRoleUser user) {
        if (StringUtils.isNotEmpty(user.getExt3())) {
            // 查询所属一级子公司的人
            List<String> deptList = new ArrayList<>();
            List<XtzyCompany> companyList = xtzyCompanyService.getParantAndChildrens(user.getExt3());
            for (XtzyCompany xtzyCompany : companyList) {
                deptList.add(xtzyCompany.getCompCode());
            }
            return roleUserMapper.selectByUserCode(user, deptList);
        }
        return roleUserMapper.selectByUserCode(user, null);
    }
    @Override
    public List<XtzyCompUserVO> selectCompUserList(String compCode, String userCode){
        return compUserMapper.selectCompUserList(compCode,userCode);
    }

	@Override
	@Transactional
	public void replace(XtzyRoleUserReplaceBO replaceBO) throws Exception{
		String newUserCode = replaceBO.getNewUser().getUserCode();
		String compCode = replaceBO.getCompCode();
    	XtzyUser us = userService.selectByName(newUserCode);
    	if(us==null){
    		//检查人员信息表中是否存在数据，如果不存在，则新增数据；
    		XtzyUser user = (XtzyUser) BeanUtils.initBean(replaceBO.getNewUser());
    		user.setUserType(replaceBO.getUserType());
    		user.setStatus("10");
    		userService.insertUser(user);
    	}else{
    		//人员信息存在，检查人员是否启用，如果禁用，则启用人员
    		us.setStatus("10");
    		userService.update(us);
    	}
    	
    	XtzyCompUser compUserParam = new XtzyCompUser();
    	compUserParam.setCompCode(compCode);
    	compUserParam.setUserCode(newUserCode);
    	int count = compUserMapper.selectCount(compUserParam);
    	//检查T_XTZY_COMP_USER ,按单位编码、人员工号，是否存在，如果存在，不能新增
    	if(count==0){
    		//替换原人员的所有角色，为新的人员
    		String oldUserCode = replaceBO.getOldUser().getUserCode();
    		XtzyRoleUser roleUserParam = new XtzyRoleUser();
        	roleUserParam.setUserCode(oldUserCode);
        	List<XtzyRoleUser> roleUsers = roleUserMapper.select(roleUserParam);
        	List<String> roleCodes = new ArrayList<String>();
        	for(XtzyRoleUser roleUser : roleUsers){
        		roleCodes.add(roleUser.getRoleCode());
        		roleUser.setUserGuid(replaceBO.getNewUser().getId());
        		roleUser.setUserCode(replaceBO.getNewUser().getUserCode());
        		roleUser.setUserDesc(replaceBO.getNewUser().getUserDesc());
        		roleUserMapper.updateByPrimaryKey(roleUser);
        	}
        	
        	//替换T_XTZY_COMP_USER
    		XtzyCompUser param = new XtzyCompUser();
    		param.setUserCode(oldUserCode);
    		param.setCompCode(replaceBO.getCompCode());
        	XtzyCompUser compUser = compUserMapper.selectOne(param);
    		compUser.setUserId(replaceBO.getNewUser().getId());
    		compUser.setUserCode(replaceBO.getNewUser().getUserCode());
    		compUser.setUserDesc(replaceBO.getNewUser().getUserDesc());
    		compUserMapper.updateByPrimaryKey(compUser);
        	
    		//执行替换逻辑
    		roleShiftService.run(compCode,newUserCode,oldUserCode,roleCodes);
    	}else{
    		throw new Exception("该人员已经存在在该机构下，不能新增");
    	}
	}
    
}
